<template>
  <div class="sms_code">
    <button
      class="sms_code_btn"
      v-if="!buttonClicked"
      :class="mobileNoIsValid ? '' : 'disable' "
      :disabled="!mobileNoIsValid"
      @click.self="getSmsCode">
      获取验证码
    </button>
    <button
      class="sms_code_clicked_btn"
      v-if="buttonClicked">
      {{ buttonText }}
    </button>
  </div>
</template>

<script type="text/babel">
  export default {
    name: 'SmsCode',
    props: {
      mobileNoIsValid: Boolean,
      mobileNo: String,
      codeType: String,
    },
    data() {
      return {
        timer: null,
        second: 119,
        buttonClicked: false,
        buttonText: ''
      };
    },
    methods: {
      getSmsCode() {
        // 根据手机号获取验证码
        this.$store.dispatch('getSmsCode', { mobileNo: this.mobileNo, codeType: this.codeType }).then(() => {

          this.setSmsCodeTimer();

        }).catch(() => {

          clearInterval(this.timer);

        });

      },
      setSmsCodeTimer() {

        this.buttonClicked = true;

        this.buttonText = '120s后可重发';

        this.timer = setInterval(() => {

          this.buttonText = this.second + 's后可重发';

          this.second -= 1;

          if (this.second <= 0) {

            this.second = 119;

            this.buttonClicked = false;

            this.buttonText = '';

            clearInterval(this.timer);

          }

        }, 1000);

      }
    }
  };
</script>

<style scoped lang="less">
  .sms_code {
    display: flex;
    align-items: center;
    flex: 0 0 auto;
    height: 100%;
    .sms_code_btn {
      height: 55px;
      outline: none;
      border: 1px solid #f7a427;
      border-radius: 80px;
      background-color: transparent;
      color: #f7a427;
      &.disable {
        border: 1px solid #e1e1e1;
        background-color: #d9d9d9;
        color: #fff;
      }
    }
    .sms_code_clicked_btn {
      height: 55px;
      outline: none;
      border: 1px solid #e1e1e1;
      border-radius: 80px;
      background-color: #d9d9d9;
      color: #fff;
    }
  }
</style>